/*
created by chuyoujun at 2018-10-18
工具文件

* */
import React from 'react';
import ReactDom from 'react-dom'

class Untils {
    constructor() {
        this.alertOPt = {
            title: "操作提醒",
            content: "",
            closeBtn: true,
            buttonText: ['取消', '确定'],
            callback: function (number) {
            }
        };
    }

    countDown(startTime, endTime, callback) {
        let startTamp = new Date(startTime).getTime();
        let endTamp = new Date(endTime).getTime();

        let timer = setInterval(() => {
            startTamp += 1000;
            let leftTime = endTamp - startTamp;
            let result = this.returnDate(startTamp, endTamp);
            if (leftTime <= 0) {
                result.show = false;
                clearInterval(timer);
            }
            callback(result)
        }, 1000)
    }

    returnDate(startTime, endTime) {
        let startTamp = new Date(startTime).getTime();
        let endTamp = new Date(endTime).getTime();
        let show = true;

        let leftTime = endTamp - startTamp;
        if (leftTime <= 0) {
            show = false
        }
        var days = Math.floor(leftTime / (24 * 3600 * 1000)).toString();
        var hourLeft = leftTime % (24 * 60 * 60 * 1000);
        var hours = Math.floor(hourLeft / (3600 * 1000)).toString();
        var minuetLeft = hourLeft % (3600 * 1000);
        var minutes = Math.floor(minuetLeft / (60 * 1000)).toString();
        var secondLeft = minuetLeft % (60 * 1000);
        var seconds = Math.round(secondLeft / 1000).toString();
        return {
            days: days >= 10 ? days : '0' + days,
            hours: hours >= 10 ? hours : '0' + hours,
            minutes: minutes >= 10 ? minutes : '0' + minutes,
            seconds: seconds >= 10 ? seconds : '0' + seconds,
            show: show
        };

    }

    getSignature(randomcode) {
        var openname = 'fwd';
        var openkey = 'fairyland';
        return openname + openkey + randomcode;
    }

    getRandomCode() {
        var date = new Date();
        return date.getTime() + this.getMathRand(5);
    }

    getMathRand(num) {
        var _val = '';
        if (typeof num !== 'number') {
            return '00000';
        }
        for (var i = 0; i < num; i++) {
            _val += Math.floor(Math.random() * 10);
        }
        return _val;
    }

    getPlatform() {
        var platforms = {
            amazon_fireos: /cordova-amazon-fireos/,
            android: /Android/,
            ios: /(iPad)|(iPhone)|(iPod)/,
            blackberry10: /(BB10)/,
            blackberry: /(PlayBook)|(BlackBerry)/,
            windows8: /MSAppHost/,
            windowsphone: /Windows Phone/
        };

        for (var key in platforms) {
            if (platforms[key].exec(navigator.userAgent)) {
                return key;
            }
        }
        return "";
    }

    loadAsycCss(className, url) {
        let name = document.getElementsByClassName(className)[0];
        if (!name) {
            let scriptEle = document.createElement('link');
            scriptEle.href = url;
            scriptEle.rel = 'stylesheet';
            scriptEle.className = className;
            document.head.appendChild(scriptEle);
        }
    }

    loadAsycJs(className, url, callback) {
        let name = document.getElementsByClassName(className)[0];
        if (!name) {
            let scriptEle = document.createElement('script');
            scriptEle.src = url;
            scriptEle.className = className;
            scriptEle.onload = function () {
                callback && callback();
            };
            scriptEle.onerror = function () {
                console.log(className + '加载失败！')
            };
            document.body.appendChild(scriptEle);
        } else {
            callback && callback();
        }
    }

    upLoadImg(ev, callback) {
        var target = ev.target;
        var file = target.files[0];
        let fileType = file.type;
        if (!(fileType == 'image/jpeg' || fileType == 'image/png')) {
            this.Alert({
                html: '请上传图片文件'
            });
            return false;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
            var result = this.result;
            callback(result)
        }
    }

    zipImg(url, obj, calback) {
        var img = new Image();
        img.src = url;
        var base64 = '';
        img.onload = function () {
            var that = this;
            // 默认按比例压缩
            var w = that.width,
                h = that.height,
                scale = w / h;
            w = obj.width || w;
            h = obj.height || (w / scale);
            var quality = 0.7;  // 默认图片质量为0.7
            //生成canvas
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            // 创建属性节点
            var anw = document.createAttribute("width");
            anw.nodeValue = w;
            var anh = document.createAttribute("height");
            anh.nodeValue = h;
            canvas.setAttributeNode(anw);
            canvas.setAttributeNode(anh);
            ctx.drawImage(that, 0, 0, w, h);
            // 图像质量
            if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
                quality = obj.quality;
            }
            // quality值越小，所绘制出的图像越模糊
            base64 = canvas.toDataURL('image/jpg', quality);
            calback(base64)
        };

    }

    getErrorRes(res) {
        let errorMsg;
        if (res.status == 500) {
            errorMsg = '服务器产生内部错误';
        } else if (res.status == 403) {
            errorMsg = '请求不允许';
        } else if (res.status == 404) {
            errorMsg = '没有发现文件、查询或URl';
        } else if (res.status == 502 || res.status == 503) {
            errorMsg = '服务暂时不可用，请重试！';
        } else {
            errorMsg = '访问错误！';
        }
        return errorMsg;
    }

    server() {
        return window.location.protocol + '//' + window.location.host;
    }

    setLocalStorage(key, value, isJson) {
        if (window.localStorage) {
            if (isJson) {
                value = JSON.stringify(value);
            }
             window.localStorage[key] = value;

        }
    }

    getLocalStorage(key, isJson) {
        if (window.localStorage) {
            var value = window.localStorage[key] || "";
            if (isJson && value) {
                value = JSON.parse(value);
            }
            return value;
        }
        return '';
    }

    showLoading() {
        let div = document.createElement('div');
        div.className = 'component-mask component-loading';
        let view = (
            <div className="spinner">
                <div className="spinner-container container1">
                    <div className="circle1"></div>
                    <div className="circle2"></div>
                    <div className="circle3"></div>
                    <div className="circle4"></div>
                </div>
                <div className="spinner-container container2">
                    <div className="circle1"></div>
                    <div className="circle2"></div>
                    <div className="circle3"></div>
                    <div className="circle4"></div>
                </div>
                <div className="spinner-container container3">
                    <div className="circle1"></div>
                    <div className="circle2"></div>
                    <div className="circle3"></div>
                    <div className="circle4"></div>
                </div>
            </div>
        );

        ReactDom.render(view, div);
        document.body.appendChild(div)
    }

    closeLoading() {
        let loading = document.getElementsByClassName('component-loading')[0];
        loading && loading.remove();
    }

    Alert(obj) {
        obj = Object.assign(this.alertOPt, obj);
        let view = (
            <div className="com-alert">
                <div className="alert-tips">
                    {obj.title}
                </div>
                <div className="alert-content">{obj.content}</div>
                <div className="alert-button">
                    {obj.closeBtn ?
                        <a className="alert-cancle" onClick={callback.bind(null, 0)}>{obj.buttonText[0]}</a> : ''}
                    <a className="alert-sure" onClick={callback.bind(null, 1)}>{obj.buttonText[1]}</a>
                </div>
            </div>

        );

        function callback(n) {
            obj.callback && obj.callback(n);
            document.getElementById('untils-alert').remove();
        }

        let div = document.createElement('div');
        div.id = 'untils-alert';
        div.className = 'component-mask';
        ReactDom.render(view, div);
        document.body.appendChild(div)
    }

    getQueryString(name) {
        var u = window.location.hash.slice(1);
        var re = new RegExp(name + '=([^&\\s+]+)');
        var m = u.match(re);
        return m ? m[1] : '';
    }

    //拆分最新动态数组

    arrayGroup(array, subGroupLength) {
        // 拆分数组
        var index = 0;
        var newArray = [];
        while (index < array.length) {
            newArray.push(array.slice(index, index += subGroupLength));
        }
        return newArray;
    }

}

export default  new Untils();


